package handler

import (
	"context"
	"github.com/golang/protobuf/ptypes/empty"
	"kop/libs/database"
	"kop/modules/ring/configuration"
	"kop/modules/ring/models"
	"kop/pb"
	"kop/pb/service"
)

type RingServiceHandler struct {
}

func (h RingServiceHandler) GetRings(ctx context.Context, req *service.RoleRequest, resp *service.Rings) error {

	resp.Rings = models.GetRings(database.DB, req.RoleID)
	return nil
}

func (h RingServiceHandler) GetByRingID(ctx context.Context, req *service.DefaultRequest, resp *service.Rings) error {

	resp.Rings = models.GetByRingID(database.DB, req.RoleID, req.Value)
	return nil
}

func (h RingServiceHandler) GetRing(ctx context.Context, req *service.DefaultRequest, ring *pb.Ring) error {

	var err error
	*ring, err = models.GetRing(database.DB, req.RoleID, req.Value)
	return err
}

func (h RingServiceHandler) Create(ctx context.Context, req *service.DefaultRequest, ring *pb.Ring) error {

	var _, err = configuration.GetByRingID(req.Value)
	if err != nil {
		return err
	}

	*ring = models.Create(database.DB, req.RoleID, req.Value)
	return nil
}

func (h RingServiceHandler) Save(ctx context.Context, req *service.RingRequest, ring *pb.Ring) error {

	*ring = *req.Ring
	models.Save(database.DB, req.RoleID, ring)

	return nil
}

func (h RingServiceHandler) Make(ctx context.Context, req *service.RingMakeRequest, rings *service.Rings) (err error) {

	var session = database.DB.Begin()
	if session.Error != nil {
		return session.Error
	}

	defer func() {
		if r := recover(); r != nil {
			err = r.(error)
		}
		if err != nil {
			session.Rollback()
		}
	}()

	models.Delete(session, req.IDs)

	for i := 0; i < len(req.IDs)/3; i++ {
		var ring = models.Create(session, req.RoleID, req.RingID)
		rings.Rings = append(rings.Rings, &ring)
	}

	return session.Commit().Error
}

func (h RingServiceHandler) Delete(ctx context.Context, req *pb.Int32Slice, e *empty.Empty) error {

	models.Delete(database.DB, req.Slices)
	return nil
}
